import _ from 'underscore'
import dispatcher from 'lib/dispatcher'
import {Scope} from 'lib/scopeFactory'

import TimeStore from 'lib/stores/time-store'
import {coreApi,sortMap,parseToChart} from '../apis/core-util'
import basicInfo from '../apis/basicInfo'

export default class MainScope extends Scope {
  constructor(props){
    super();
    this.appversionId = props.routeParams.appversionId
    this.$state = {
      title:'',
      chart0:{
        loading:true
      },
      chart1:{
        loading:true
      }
    }
    this.basicInfo = basicInfo({
      id:this.appversionId,
      urlName:'appversion'
    })
    this.chart0Api = coreApi({
      limit:5,
      classify:'appversion',
      viewKey:'avg_exec',
      urlName:'interaction'
    },TimeStore.getValue,function (){
      return {order:sortMap[this.viewKey]}
    },function(){
      return {
        appVersionId:this.appversionId
      }
    }.bind(this));
    this.chart1Api = coreApi({
      limit:5,
      classify:'appversion',
      viewKey:'session_count',
      urlName:'session'
    },TimeStore.getValue,function (){
      return {order:sortMap[this.viewKey]}
    },function(){
      return {
        appVersionId:this.appversionId
      }
    }.bind(this));
  }
  fetch(){
    var _this = this
    this.chart0Api.fetch().then(function(data,params){
      _this.$state.chart0 = {
        data:parseToChart(data,params)
      }
    },function(err){
      _this.$state.chart0 = {
        error:err
      }
    },function(params){
      _this.$state.chart0 = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    })
    this.chart1Api.fetch().then(function(data,params){
      _this.$state.chart1 = {
        data:parseToChart(data,params)
      }
    },function(err){
      _this.$state.chart1 = {
        error:err
      }
    },function(params){
      _this.$state.chart1 = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    })
  }
  $settime(payload){
    this.fetch()
  }
  $unload(){
  }
  $load(){
    var _this = this
    this.basicInfo.fetch().done(function(data){
      //TODO 当basicInfo查不到时应显示错误,可以在Router.transtition时加载basicInfo并判断
      _this.$state.title = data.result[0].name;
      _this.emit()
    })
    this.fetch();

  }
}
